#!/usr/bin/python
import db_util
import sys
import os
import time

myhost = db_util.getDBHost() #config.get("mysql_jdbc_configs", "host")
mydb = db_util.getDBSchema() #config.get("mysql_jdbc_configs", "db")
myuser = db_util.getDBUser() #config.get("mysql_jdbc_configs", "username")
mypw = db_util.getDBPassword() #config.get("mysql_jdbc_configs", "password")


print "Parsing features kicked off %s" %time.ctime()
#infile = open('KruglyakGenewisePhenoProteomics_associations.tsv');
if (len(sys.argv) != 3):
	print 'Usage is py2.6 parse_features_kruglyak.py ./input/associations.tsv dataset_label'
	sys.exit(1)

infile = open(sys.argv[1])
dataset_label = sys.argv[2]
schema = mydb
feature_table = schema + "." + dataset_label + "_features" #sys.argv[3]
#feature_helper = {}
#feature_helper["IMP2"] = "C:GENO:IMP2:chrIX:53981:55021:-"
#feature_helper["AAP1"] = "C:GENO:AAP1:chrVIII:198740:201310:-"
features_hash = {}
fshout = open('load_features_' + dataset_label + '.sh','w')
outfile = open('./features_out_' + dataset_label + '.tsv','w')
fromPred = 0
fromTarget = 0
for line in infile:
	tokens = line.split('\t')
	#if (tokens[0].find("'") != -1 or tokens[1].find("'") != -1):
		#print tokens[0] + "\t" + tokens[1]
		#if (tokens[0].find('IMP2') != -1):
		#	tokens[0] = feature_helper.get("IMP2")
		#if (tokens[1].find('IMP2') != -1):
		#	tokens[1] = feature_helper.get("IMP2")
		#if (tokens[0].find('AAP1') != -1):
		#	tokens[0] = feature_helper.get("AAP1")	
		#if (tokens[1].find('AAP1') != -1):
		#	tokens[1] = feature_helper.get("AAP1")
	#if (tokens[0].find('PHENO') != -1):
	#	tokens[0] = yeast_util.transPhenoFeature(tokens[0])
	#if (tokens[1].find('PHENO') != -1):
	#	tokens[1] = yeast_util.transPhenoFeature(tokens[1])

	if (not features_hash.get(tokens[0])):
		features_hash[tokens[0]] = tokens[0]
		#tokenize feature alias and then add to tsv
		data = tokens[0].split(':')
		if len(data) > 4 and len(data[3]) > 3:
			data[3] = data[3][3:]
		outfile.write(tokens[0] + "\t" + "\t".join(data) + "\n")
		fromPred = fromPred + 1
	if (not features_hash.get(tokens[1])):
		features_hash[tokens[1]] = tokens[1]
		data = tokens[1].split(':')
		if len(data) > 4 and len(data[3]) > 3:
                        data[3] = data[3][3:]
                outfile.write(tokens[1] + "\t" + "\t".join(data) + "\n")
		fromTarget = fromTarget + 1			
infile.close()
outfile.close()
fshout.write("#!/bin/bash\n")
fshout.write("mysql --user=%s --password=%s --database=%s<<EOFMYSQL\n" %(myuser, mypw, mydb))
fshout.write("load data local infile './" + outfile.name + "' replace INTO TABLE " + feature_table + " fields terminated by '\\t' LINES TERMINATED BY '\\n';")
fshout.write("\ncommit;")
fshout.write("\nEOFMYSQL")
fshout.close()
print "parsing done, running bulk load data to mysql %s" %time.ctime()
os.system("sh " + fshout.name)
